package com.liyuanjinglyj.csdncard.utils;

import ohos.utils.zson.ZSONArray;
import ohos.utils.zson.ZSONObject;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import javax.net.ssl.HttpsURLConnection;
import java.io.IOException;
import java.net.URL;

public class LYJUtils {
    /**
     * 获取重定向地址
     */
    public static String getRedirectUrl(String url) throws IOException {
        HttpsURLConnection conn = (HttpsURLConnection) new URL(url).openConnection();
        conn.setInstanceFollowRedirects(false);
        conn.setConnectTimeout(5000);
        return conn.getHeaderField("Location");
    }

    public static void getData(ZSONObject zsonObject,ZSONArray zsonArray,String url) {
        try {
            Connection connect = Jsoup.connect(url);
            Connection conheader = connect.header("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36");
            Document doc = conheader.get();
            Element head_img=doc.selectFirst(".avatar_pic");
            String head_img_url=head_img.attr("src");
            Element name_ele=doc.selectFirst(".title-box");
            String name=name_ele.selectFirst("a").text();
            String content=name_ele.selectFirst("p").text();
            //zsonObject.put("head",head_img_url);
            zsonObject.put("name",name);
            if(content.length()>40){
                zsonObject.put("content",content.substring(0,40));
            }else{
                zsonObject.put("content",content);
            }
            Elements list_blog = doc.select(".article-item-box");
            int i=0;
            for (Element div : list_blog) {
                if(i==10){
                    break;
                }
                String titleStr = div.select("h4 a").text();
                String contentStr = div.select(".content").text();
                ZSONObject zsonObject1=new ZSONObject();
                zsonObject1.put("title",titleStr.replace("原创 ",""));
                zsonObject1.put("content",contentStr.substring(0,20));
                zsonObject1.put("url",div.select("h4 a").attr("href"));
                zsonArray.add(zsonObject1);
                i++;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
